package com.jc.service.gameinterface;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.Base64Util;
import com.jc.common.util.CryptoUtils;
import com.jc.common.util.ExceptionUtil;
import com.jc.common.util.HttpUtil;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.GameUser;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.GameServerApi;
import com.jc.framework.enums.LogType;
import com.jc.service.apilog.ApiLogService;
import com.jc.service.gameuser.GameUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class GameInterfaceServiceImpl implements GameInterfaceService {
    private final Logger LOGGER = LoggerFactory.getLogger(GameInterfaceServiceImpl.class);
    @Value("${user.encrypt}")
    private String userEncrypt;
    @Value("${game.url}")
    private String gameUrl;
    @Autowired
    private ApiLogService apiLogService;
    @Autowired
    private GameUserService gameUserService;

    @Override
    public Map<String, Object> gameInterfaceHttp(GameServerApi gameServerApi, Map<String, Object> param,LogType logType) {
        String s = "";
        try {
            for (String key:param.keySet()) {
                if (param.get(key) == null){
                    param.put(key,"");
                }
                param.put(key, Base64Util.encode(CryptoUtils.encrypt(param.get(key).toString(),userEncrypt)));
            }
            LOGGER.error(param.toString());
            s = HttpUtil.post(gameUrl+gameServerApi.getName(), param);
            Map map = JSONObject.parseObject(s, Map.class);
            if (map.get("success")!=null && map.get("success").toString().equals("1")){
                //成功
                apiLogService.addApiLog(logType,JSONObject.toJSONString(param), Conclusion.OK,"",s);
                return map;
            }else{
                apiLogService.addApiLog(logType,JSONObject.toJSONString(param), Conclusion.FAIL,"",s);
                return map;
            }
        } catch (Exception e) {
            LOGGER.error("与游戏服务器通信过程中出现网络错误, {},{}" , e.getMessage(),e);
            apiLogService.addApiLog(logType,JSONObject.toJSONString(param), Conclusion.FAIL, ExceptionUtil.subExceptionMessage(e, 0, 200),s);
            e.printStackTrace();
        }
        return null;
    }

    //查询余额
    @Override
    public Map<String,Object> getGameBalance(Long userId){
        GameUser gameUser = gameUserService.queryGameUser(userId);
        if (gameUser == null){
            throw new BaseServiceException("当前用户不存在");
        }
        Map<String, Object> resultMap = this.gameInterfaceHttp(GameServerApi.AMOUNT_QUERY, new HashMap<String, Object>() {{
            put("userId",userId);
            put("name",gameUser.getUserNickName());
            put("head",gameUser.getUserPic());
        }},LogType.GAME_USER_BALANCE);
        if (resultMap == null){
            throw new BaseServiceException("查询用户金币余额失败");
        }
        return resultMap;
    }

    /***
     * 充值提现
     * userId 二号系统Id   amount 金币
     *
     *
     * return
     *      success  0 失败 1 成功
     *      message 错误描述信息
     *      amount  当前金币余额
     * */
    @Override
    public Map<String,Object> rechargeOrWithdraw(Long userId, BigDecimal amount){
        GameUser gameUser = gameUserService.queryGameUser(userId);
        if (gameUser == null){
            throw new BaseServiceException("当前用户不存在");
        }
        Map<String, Object> resultMap = this.gameInterfaceHttp(GameServerApi.RECHARGE_WITHDRAW, new HashMap<String, Object>() {{
            put("userId", gameUser.getUserId());
            put("name", gameUser.getUserNickName());
            put("head", gameUser.getUserPic());
            put("amount", amount);
        }},LogType.GAME_USER_RECHARGEORWITHDRAW);
        if (resultMap == null){
            throw new BaseServiceException("充值提现失败");
        }
        return resultMap;
    }
}
